package com.h3bpm.starcharge.service.impl.k3c;
import com.h3bpm.starcharge.bean.k3c.LastNumber;
import com.h3bpm.starcharge.common.bean.RestfulErrorCode;
import com.h3bpm.starcharge.bean.k3c.SupplierInfo.Linkman;
import com.h3bpm.starcharge.bean.k3c.SupplierInfo.BankInfo;
import java.util.ArrayList;

import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.h3bpm.starcharge.bean.k3c.SupplierInfo;
import com.h3bpm.starcharge.bean.k3c.SupplierView;
import com.h3bpm.starcharge.common.bean.*;
import com.h3bpm.starcharge.common.uitl.*;
import com.h3bpm.starcharge.common.uitl.k3c.K3cUtil;
import com.h3bpm.starcharge.config.K3CloundConfig;
import com.h3bpm.starcharge.ret.k3c.K3cBase;
import com.h3bpm.starcharge.service.k3c.BaseDataService;
import com.h3bpm.starcharge.service.k3c.K3cService;
import com.h3bpm.starcharge.service.k3c.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * K3C供应商接口
 *
 * @author LLongAgo
 * @date 2019/4/11
 * @since 1.0.0
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private K3cUtil util;
    @Autowired
    private K3cService k3cService;
    @Autowired
    private K3CloundConfig k3CloundConfig;
    @Autowired
    private BaseDataService baseDataService;

    @Value("${k3c_dbId}")
    private String dbId;
    @Value("${k3c_uid}")
    private String uid;
    @Value("${k3c_pwd}")
    private String pwd;
    @Value("${k3c_lang}")
    private int lang;
    @Value("${golangApiUrl}")
    private String golangApiUrl;

    private static final String STAR_CHARGE = "星充";
    private static final String GUO_CHUANG = "国创";
    private static final String FORM_ID = "BD_Supplier";
    private static final String CONTACT_FORM_ID = "BD_CommonContact";

    /**
     * 保存
     * @param instanceData  InstanceData
     * @return RetResult
     */
    @Override
    public RetResult save(InstanceData instanceData) throws Exception {
        HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
        JSONObject basic = setSaveParam(valueTable);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("formid", FORM_ID);
        jsonObject.put("data", basic);
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
        String cookie = util.getLoginCookie();
        // 保存
        RetResult result = k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSave(), cookie, param);
        if (!RestfulErrorCode.SUCCESS.getCode().equals(result.getCode())) {
            return result;
        }
        K3cBase k3cBase = (K3cBase) result.getData();
        String submitParam = k3cService.buildParam(FORM_ID, k3cBase.getId(), null, null);
        // 提交
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSubmit(), cookie, submitParam);
        // 审核
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getAudit(), cookie, submitParam);
        // 根据使用组织分配
        String useOrganization = (String) valueTable.get("useOrganization");
        JsonResult<List<BaseResult>> organizationList;
        StringBuilder sb = new StringBuilder();
        if (useOrganization.equals(GUO_CHUANG)) {
            organizationList = baseDataService.getOrganizationBySql("FNUMBER like '104%'");
        } else if (useOrganization.equals(STAR_CHARGE)) {
            organizationList = baseDataService.getOrganizationBySql("FNUMBER like '102%'");
        } else {
            organizationList = baseDataService.getOrganizationBySql("FNUMBER = 101");
        }
        List<BaseResult> data = organizationList.getData();
        for (BaseResult d : data) {
            sb.append(d.getValue()).append(",");
        }
        String orgStr = sb.toString();
        orgStr = orgStr.substring(0, orgStr.length() - 1);
        // 拼接分配参数
        String allocateParam = k3cService.buildAllocateParam(FORM_ID, orgStr, k3cBase.getId());
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getAllocate(), cookie, allocateParam);
        // 绑定联系人
        BizObject[] bizObjects = (BizObject[]) valueTable.get("linkmanSupplier");
        if (null != bizObjects && bizObjects.length > 0) {
            String ids = (String) basic.get("contactIds");
            String numbers = (String) basic.get("contactNumbers");
            String[] contactIds = ids.split(",");
            String[] contactNumbers = numbers.split(",");
            String number = ((K3cBase) result.getData()).getId();
            for (int i = 0; i < bizObjects.length; i++) {
                HashMap<String, Object> vb = bizObjects[i].getValueTable();
                contactBindSupplier(vb, contactIds[i], contactNumbers[i], number);
            }
            contactBindCustomer(ids, number);
        }
        return result;
    }

    /**
     * 设置保存参数
     */
    private JSONObject setSaveParam(HashMap<String, Object> valueTable) throws Exception {
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/supplier-save.json");
        JSONObject basic = JSON.parseObject(template);
        JSONObject model = basic.getJSONObject("Model");
        // 设置公共参数
        setParam(model, valueTable);
        // 组织信息
        List<Map<String, Object>> locationInfos = new ArrayList<>();
        List<Map<String, Object>> supplierContact = new ArrayList<>();
        BizObject[] bizObjects = (BizObject[]) valueTable.get("linkmanSupplier");
        if (null != bizObjects && bizObjects.length > 0) {
            // 保存联系人
            RetResult retResult = saveContact(bizObjects);
            if (RestfulErrorCode.SUCCESS.getCode().equals(retResult.getCode())) {
                K3cBase k3cBase = (K3cBase) retResult.getData();
                // 字符串转数组
                String[] contacts = k3cBase.getNumber().split(",");
                String[] ids = k3cBase.getId().split(",");
                basic.put("contactIds", k3cBase.getId());
                basic.put("contactNumbers", k3cBase.getNumber());
                for (int i = 0; i < bizObjects.length; i++) {
                    Map<String, Object> location = new HashMap<>(8);
                    Map<String, Object> contact = new HashMap<>(2);
                    HashMap<String, Object> vb = bizObjects[i].getValueTable();
                    String name = (String) vb.get("addressName");
                    String address = (String) vb.get("address");
                    String mobile = (String) vb.get("mobile");
                    location.put("FLocNumber", Md5Util.getMD5(name + address + mobile, true, 16));
                    MapUtil.batchSet(location, vb, new String[]{"FLocName", "FLocAddress", "FLocMobile"},
                            new String[]{"addressName", "address", "mobile"});
                    Map<String, Object> newContact = new HashMap<>(2);
                    newContact.put("FNUMBER", contacts[i]);
                    location.put("FLocNewContact", newContact);
                    contact.put("FContactId", ids[i]);
                    supplierContact.add(contact);
                    locationInfos.add(location);
                }
            }
        }
        model.put("FLocationInfo", locationInfos);
        model.put("FSupplierContact", supplierContact);
        return basic;
    }

    /**
     * 设置通用参数
     */
    private void setParam(JSONObject model, HashMap<String, Object> valueTable) throws Exception {
        if (null != valueTable.get("supplierId")) {
            model.put("FSupplierId", valueTable.get("supplierId"));
        }
        // 保存--获取最新的编码
        String customerCode = (String) valueTable.get("customerCode");
        if ("".equals(customerCode.trim())) {
            Map<String, String> postMap = new HashMap<>(2);
            postMap.put("group", (String) valueTable.get("customerGroupId"));
            String json = OkHttpUtil.post(golangApiUrl + "supplier/lastNumber", postMap);
            LastNumber lastNumber = new Gson().fromJson(json, LastNumber.class);
            valueTable.put("customerCode", lastNumber.getData().getFnumber());
        }

        MapUtil.batchSet(model, valueTable, new String[] {"FNumber", "FName", "F_GSDH_Text", "F_ZLQ", "F_WB_YFKTJ", "F_WB_DLSTXRZ"},
                new String[] {"customerCode", "customerName", "companyTel", "qualityPeriod", "YFKTJ", "DLSTXRZ"});
        Date date = (Date) valueTable.get("GYSZSYXQ");
        model.put("F_WB_DLSZSYXQ", DateUtil.dateToString(date, "yyyy-MM-dd hh:mm:ss"));
        model.put("F_WB_YCTXRZ", valueTable.get("YCTXRZ"));
        model.put("F_WB_JGCTXRZ", valueTable.get("JGTXRZ"));
        date = (Date) valueTable.get("YCZSYXQ");
        model.put("F_WB_YCZSYXQ", DateUtil.dateToString(date, "yyyy-MM-dd hh:mm:ss"));
        date = (Date) valueTable.get("JGCZSYXQ");
        model.put("F_WB_Date", DateUtil.dateToString(date, "yyyy-MM-dd hh:mm:ss"));
        // 供应商分组
        Map<String, Object> group = new HashMap<>(4);
        group.put("FNumber", valueTable.get("customerGroupId"));
        model.put("FGroup", group);
        // 供应商关联类型
        Map<String, Object> cognateType = new HashMap<>(4);
        cognateType.put("FNumber", valueTable.get("cognateType"));
        model.put("F_WB_GYSGLLX", cognateType);
        // 基本信息
        Map<String, Object> baseInfo = new HashMap<>(8);
        // 国家
        Map<String, Object> country = new HashMap<>(2);
        country.put("FNumber", valueTable.get("country"));
        baseInfo.put("FCountry", country);
        MapUtil.batchSet(baseInfo, valueTable, new String[] {"FAddress", "FRegisterAddress", "FSupplyClassify", "FSOCIALCRECODE"},
                new String[] {"address", "registeredAddress", "supplierCategory", "TYSHXYDM"});
        // 供应商分类
        Map<String, Object> supplierType = new HashMap<>(2);
        supplierType.put("FNumber", valueTable.get("supplierType"));
        baseInfo.put("FSupplierClassify", supplierType);
        // 供应商等级
        Map<String, Object> supplierLevel = new HashMap<>(2);
        supplierLevel.put("FNumber", valueTable.get("supplierLevel"));
        baseInfo.put("FSupplierGrade", supplierLevel);
        model.put("FBaseInfo", baseInfo);
        // 商务信息
        Map<String, Object> businessInfo = new HashMap<>(4);
        // 结算方式
        Map<String, Object> clearType = new HashMap<>(2);
        clearType.put("FNumber", valueTable.get("clearType"));
        businessInfo.put("FSettleTypeId", clearType);
        businessInfo.put("FVmiBusiness", false);
        businessInfo.put("FEnableSL", false);
        model.put("FBusinessInfo", businessInfo);
        // 财务信息
        Map<String, Object> financeInfo = new HashMap<>(8);
        // 结算币别
        Map<String, Object> currency = new HashMap<>(2);
        currency.put("FNumber", valueTable.get("currency"));
        financeInfo.put("FPayCurrencyId", currency);
        // 付款条件
        Map<String, Object> collection = new HashMap<>(2);
        collection.put("FNumber", valueTable.get("collection"));
        financeInfo.put("FPayCondition", collection);
        // 税分类
        Map<String, Object> taxType = new HashMap<>(2);
        taxType.put("FNumber", valueTable.get("taxType"));
        financeInfo.put("FTaxType", taxType);
        financeInfo.put("FTaxRegisterCode", valueTable.get("NSDJH"));
        financeInfo.put("FInvoiceType", valueTable.get("invoiceType"));
        // 默认税率
        Map<String, Object> defaultTax = new HashMap<>(2);
        defaultTax.put("FNumber", valueTable.get("defaultTax"));
        financeInfo.put("FTaxRateId", defaultTax);
        model.put("FFinanceInfo", financeInfo);
        // 银行信息
        List<Map<String, Object>> banks = new ArrayList<>();
        BizObject[] zbBizObjects = (BizObject[]) valueTable.get("bankInfoSupplier");
        if (null == zbBizObjects) {
            zbBizObjects = (BizObject[]) valueTable.get("bankInfoSupplierEdit");
        }
        if (null != zbBizObjects && zbBizObjects.length > 0) {
            for (BizObject object : zbBizObjects) {
                HashMap<String, Object> table = object.getValueTable();
                Map<String, Object> bank = new HashMap<>(8);
                if (null != table.get("bankId")) {
                    bank.put("FBankId", table.get("bankId"));
                }
                MapUtil.batchSet(bank, table, new String[] {"FOpenBankName", "FBankCode", "FBankHolder", "FOpenAddressRec"},
                        new String[] {"bank", "account", "accountName", "address"});
                Map<String, Object> bCurrency = new HashMap<>(4);
                bCurrency.put("FNumber", valueTable.get("currency"));
                bank.put("FBankCurrencyId", bCurrency);
                bank.put("FBankIsDefault", false);
                banks.add(bank);
            }
            model.put("FBankInfo", banks);
        } else {
            model.put("FBankInfo", banks);
        }
    }

    /**
     * 保存联系人
     * @param zbBizObjects  BizObject[]
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private RetResult saveContact(BizObject[] zbBizObjects) throws Exception {
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/contact-save-batch.json");
        JSONObject basic = JSON.parseObject(template);
        // 获取model数组
        JSONArray jsonArray = basic.getJSONArray("Model");
        Map<String, Object> modelTemplate = (Map<String, Object>) jsonArray.get(0);
        jsonArray.clear();
        for (BizObject zbBizObject : zbBizObjects) {
            Map<String, Object> model = new HashMap<>(32);
            model.putAll(modelTemplate);
            Map<String, Object> zbValueTable = zbBizObject.getValueTable();
            String name = (String) zbValueTable.get("addressName");
            String address = (String) zbValueTable.get("address");
            String mobile = (String) zbValueTable.get("mobile");
            model.put("FBIZLOCNUMBER", Md5Util.getMD5(name + address + mobile, true, 16));
            String[] keys = {"FNAME", "FPOST", "FMOBILE", "FCOMPANYTYPE", "FEMAIL", "FBIZLOCATION", "FBIZADDRESS"};
            String[] values = {"linkName", "duty", "mobile", "type", "email", "addressName", "address"};
            MapUtil.batchSet(model, zbValueTable, keys, values);
            jsonArray.add(model);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("formid", CONTACT_FORM_ID);
        jsonObject.put("data", basic);
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
        // 登录
        String loginParam = k3cService.buildLogin(dbId, uid, pwd, lang);
        RetResult loginResult = k3cService.login(k3CloundConfig.getUrl() + k3CloundConfig.getLogin(), loginParam);
        if (!loginResult.getCode().equals(RestfulErrorCode.SUCCESS.getCode())) {
            return loginResult;
        }
        // 取出登录cookie
        Map<String, Object> loginMap = (Map<String, Object>) loginResult.getData();
        String cookie = loginMap.get("cookie").toString();
        // 保存
        return k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getBatchSave(), cookie, param);
    }

    /**
     * 修改联系人
     */
    @SuppressWarnings("unchecked")
    private RetResult editContact(Map<String, Object> vb, String cookie) throws Exception {
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/contact-save-batch.json");
        JSONObject basic = JSON.parseObject(template);
        // 获取model数组
        JSONArray jsonArray = basic.getJSONArray("Model");
        Map<String, Object> modelTemplate = (Map<String, Object>) jsonArray.get(0);
        jsonArray.clear();
        Map<String, Object> model = new HashMap<>(16);
        model.putAll(modelTemplate);
        String[] keys = new String[] {"FPOST", "FEMAIL", "FNAME", "FBIZLOCATION", "FBIZADDRESS", "FMOBILE", "FCOMPANYTYPE"};
        String[] values = new String[] {"duty", "email", "linkName", "addressName", "address", "mobile", "type"};
        MapUtil.batchSet(model, vb, keys, values);
        jsonArray.add(model);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("formid", CONTACT_FORM_ID);
        jsonObject.put("data", basic);
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
        // 保存
        return k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getBatchSave(), cookie, param);
    }

    /**
     * 供应商详情
     * @param number    编码
     * @return  RetResult
     * @throws Exception
     */
    @Override
    public RetResult info(String number) throws Exception {
        String result = util.view(FORM_ID, String.format("{\"CreateOrgId\":0,\"Number\":\"%s\",\"Id\":\"\"}", number));
        SupplierView supplierView = new Gson().fromJson(result, SupplierView.class);
        if (null != supplierView.getResult().getResponseStatus()) {
            return RetResponse.makeErrRsp("该供应商不存在!");
        }

        SupplierView.ResultBeanX.ResultBean resultBean = supplierView.getResult().getResult();
        SupplierInfo supplierInfo = new SupplierInfo();
        supplierInfo.setCustomerName(resultBean.getName().get(0).getValue());
        supplierInfo.setCustomerCode(resultBean.getNumber());
        supplierInfo.setCountry(resultBean.getSupplierBase().get(0).getCountry().getFNumber());
        supplierInfo.setAddress(resultBean.getSupplierBase().get(0).getAddress());
        supplierInfo.setQualityPeriod(resultBean.getF_ZLQ());
        supplierInfo.setYFKTJ(resultBean.getF_WB_YFKTJ());
        supplierInfo.setCompanyTel(resultBean.getF_GSDH_Text());
        supplierInfo.setTYSHXYDM(resultBean.getSupplierBase().get(0).getSOCIALCRECODE());
        supplierInfo.setRegisteredAddress(resultBean.getSupplierBase().get(0).getRegisterAddress());
        supplierInfo.setSupplierType(null != resultBean.getSupplierBase().get(0).getSupplierClassify() ? resultBean.getSupplierBase().get(0).getSupplierClassify().getFNumber() : "");
        supplierInfo.setSupplierCategory(resultBean.getSupplierBase().get(0).getSupplyClassify());
        supplierInfo.setSupplierLevel(resultBean.getSupplierBase().get(0).getSupplierGrade().getFNumber());
        supplierInfo.setCustomerGroup(resultBean.getFGroup().getName().get(0).getValue());
        supplierInfo.setCognateType(resultBean.getF_WB_GYSGLLX().getFNumber());
        supplierInfo.setDLSTXRZ(resultBean.getF_WB_DLSTXRZ());
        supplierInfo.setGYSZSYXQ(null != resultBean.getF_WB_DLSZSYXQ() ? resultBean.getF_WB_DLSZSYXQ() : "");
        supplierInfo.setYCTXRZ(resultBean.getF_WB_YCTXRZ());
        supplierInfo.setYCZSYXQ(null != resultBean.getF_WB_YCZSYXQ() ? resultBean.getF_WB_YCZSYXQ() : "");
        supplierInfo.setJGTXRZ(resultBean.getF_WB_JGCTXRZ());
        supplierInfo.setJGCZSYXQ(null != resultBean.getF_WB_Date() ? resultBean.getF_WB_Date() : "");
        supplierInfo.setCurrency(resultBean.getSupplierFinance().get(0).getPayCurrencyId().getNumber());
        supplierInfo.setClearType(null != resultBean.getSupplierBusiness().get(0).getSettleTypeId() ? resultBean.getSupplierBusiness().get(0).getSettleTypeId().getNumber() : "");
        supplierInfo.setCollection(null != resultBean.getSupplierFinance().get(0).getPayCondition() ? resultBean.getSupplierFinance().get(0).getPayCondition().getNumber() : "");
        supplierInfo.setTaxType(resultBean.getSupplierFinance().get(0).getFTaxType().getFNumber());
        supplierInfo.setNSDJH(resultBean.getSupplierFinance().get(0).getTaxRegisterCode());
        supplierInfo.setInvoiceType(resultBean.getSupplierFinance().get(0).getInvoiceType());
        supplierInfo.setDefaultTax(null != resultBean.getSupplierFinance().get(0).getTaxRateId() ? resultBean.getSupplierFinance().get(0).getTaxRateId().getNumber() : "");
        supplierInfo.setCustomerGroupId(resultBean.getFGroup().getNumber());
        ArrayList<BankInfo> bankInfos = new ArrayList<>();
        List<SupplierView.ResultBeanX.ResultBean.SupplierBankBean> supplierBank = resultBean.getSupplierBank();
        if (null != supplierBank && supplierBank.size() > 0) {
            for (SupplierView.ResultBeanX.ResultBean.SupplierBankBean bank : supplierBank) {
                if (bank.getId() > 0) {
                    BankInfo bankInfo = new BankInfo();
                    bankInfo.setId(String.valueOf(bank.getId()));
                    bankInfo.setBank(bank.getOpenBankName().get(0).getValue());
                    bankInfo.setAccount(bank.getBankCode());
                    bankInfo.setAccountName(bank.getBankHolder());
                    bankInfo.setAddress(bank.getOpenAddressRec());
                    bankInfo.setCurrency(null != bank.getCurrencyId() ? bank.getCurrencyId().getNumber() : "");
                    bankInfos.add(bankInfo);
                }
            }
        }
        supplierInfo.setBankInfo(bankInfos);

        ArrayList<Linkman> linkmen = new ArrayList<>();
        List<SupplierView.ResultBeanX.ResultBean.SupplierLocationBean> supplierLocation = resultBean.getSupplierLocation();
        List<SupplierView.ResultBeanX.ResultBean.SupplierContactBean> contact = resultBean.getSupplierContact();
        int size = supplierLocation.size();
        if (supplierLocation.size() > 0) {
            for (int i = 0; i < size; i++) {
                if (supplierLocation.get(i).getId() > 0) {
                    Linkman linkman = new Linkman();
                    linkman.setId(null != contact.get(i) ? String.valueOf(contact.get(i).getCommonContactId().getId()) : "0");
                    linkman.setAddress(supplierLocation.get(i).getAddress());
                    linkman.setAddressName(supplierLocation.get(i).getName());
                    linkman.setType("BD_Supplier");
                    linkman.setDuty(supplierLocation.get(i).getNEWCONTACTID().getPost());
                    linkman.setEmail(supplierLocation.get(i).getNEWCONTACTID().getEmail());
                    linkman.setLinkName(supplierLocation.get(i).getNEWCONTACTID().getName().get(0).getValue());
                    linkman.setMobile(supplierLocation.get(i).getNEWCONTACTID().getMobile());
                    linkman.setLocId(String.valueOf(supplierLocation.get(i).getId()));
                    linkman.setNumber(supplierLocation.get(i).getNEWCONTACTID().getNumber());
                    linkmen.add(linkman);
                }
            }
        }
        supplierInfo.setLinkman(linkmen);

        return RetResponse.makeOKRsp(supplierInfo);
    }

    /**
     * 修改
     */
    @Override
    public RetResult edit(InstanceData instanceData) throws Exception {
        HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();
        JSONObject basic = setEditParam(valueTable);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("formid", FORM_ID);
        jsonObject.put("data", basic);
        // 禁止循环引用
        String param = JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
        String cookie = util.getLoginCookie();
        // 保存
        RetResult result = k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSave(), cookie, param);
        if (!RestfulErrorCode.SUCCESS.getCode().equals(result.getCode())) {
            return result;
        }
        // 反审核
        String unAuditParam = k3cService.buildParam(FORM_ID, (String) valueTable.get("supplierId"), null, null);
        RetResult unAuditResult = k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getUnAudit(), cookie, unAuditParam);
        if (!unAuditResult.getCode().equals(RestfulErrorCode.SUCCESS.getCode())) {
            return unAuditResult;
        }
        // 保存
        result = k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSave(), cookie, param);
        if (!RestfulErrorCode.SUCCESS.getCode().equals(result.getCode())) {
            return result;
        }
        K3cBase k3cBase = (K3cBase) result.getData();
        String submitParam = k3cService.buildParam(FORM_ID, k3cBase.getId(), null, null);
        // 提交
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getSubmit(), cookie, submitParam);
        // 审核
        k3cService.save(k3CloundConfig.getUrl() + k3CloundConfig.getAudit(), cookie, submitParam);
        return result;
    }

    /**
     * 设置修改参数
     * @param valueTable    HashMap<String, Object>
     * @return  JSONObject
     * @throws Exception
     */
    private JSONObject setEditParam(HashMap<String, Object> valueTable) throws Exception {
        String cookie = util.getLoginCookie();
        // 解析json模板
        String template = FileUtil.readJsonData("k3c/supplier-edit.json");
        JSONObject basic = JSON.parseObject(template);
        JSONObject model = basic.getJSONObject("Model");
        // 设置公共参数
        setParam(model, valueTable);
        // 组织信息
        List<Map<String, Object>> locationInfos = new ArrayList<>();
        BizObject[] bizObjects = (BizObject[]) valueTable.get("linkmanSupplierEdit");
        if (null != bizObjects && bizObjects.length > 0) {
            for (int i = 0; i < bizObjects.length; i++) {
                Map<String, Object> location = new HashMap<>(8);
                HashMap<String, Object> vb = bizObjects[i].getValueTable();
                if ("0".equals(vb.get("linkmanId"))) {
                    // 新增
                    RetResult retResult = editContact(vb, cookie);
                    K3cBase k3cBase = (K3cBase) retResult.getData();
                    vb.put("number", k3cBase.getNumber());
                    contactBindSupplier(vb, k3cBase.getId(), k3cBase.getNumber(), (String) valueTable.get("supplierId"));
                    contactBindCustomer(k3cBase.getId(), (String) valueTable.get("supplierId"));
                } else {
                    // 修改
                    Map<String, String> contactMap = new HashMap<>(16);
                    String[] keys = new String[] {"id", "duty", "email", "name", "addressName", "address", "mobile"};
                    String[] values = new String[] {"linkmanId", "duty", "email", "linkName", "addressName", "address", "mobile"};
                    MapUtil.batchSetString(contactMap, vb, keys, values);
                    OkHttpUtil.post(golangApiUrl + "contact/update", contactMap);
                }
                String[] keys = new String[] {"FLocationId", "FLocName", "FLocAddress", "FLocMobile"};
                String[] values = new String[] {"locId", "addressName", "address", "mobile"};
                MapUtil.batchSet(location, vb, keys, values);
                Map<String, Object> newContact = new HashMap<>(2);
                newContact.put("FNUMBER", vb.get("number"));
                location.put("FLocNewContact", newContact);
                locationInfos.add(location);
            }
        }
        model.put("FLocationInfo", locationInfos);
        return basic;
    }

    /**
     * 联系人绑定客户
     */
    private void contactBindCustomer(String ids, String number) throws Exception {
        Map<String, String> customerMap = new HashMap<>(4);
        MapUtil.batchSetString(customerMap, new String[] {"ids", "number"}, new String[] {ids, number});
        OkHttpUtil.post(golangApiUrl + "contact/contactBindCustomer", customerMap);
    }

    /**
     * 联系人绑定供应商
     */
    private void contactBindSupplier(HashMap<String, Object> vb, String contactId, String contactNumber, String supplierId) throws Exception {
        Map<String, String> supplierMap = new HashMap<>(16);
        String[] keys = new String[] {"name", "duty", "email", "mobile"};
        String[] values = new String[] {"linkName", "duty", "email", "mobile"};
        MapUtil.batchSetString(supplierMap, vb, keys, values);
        MapUtil.batchSetString(supplierMap, new String[] {"contactId", "number", "supplierId"}, new String[] {contactId, contactNumber, supplierId});
        OkHttpUtil.post(golangApiUrl + "contact/contactBindSupplier", supplierMap);
    }
}